package com.magicode.portal.service.impl;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;
import java.util.Random;

import javax.servlet.http.HttpSession;
import javax.transaction.Transactional;

import org.hibernate.Hibernate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import com.magicode.cms.entiy.base.Attitude;
import com.magicode.cms.entiy.base.Dictionary;
import com.magicode.cms.entiy.base.News;
import com.magicode.cms.entiy.base.NewsComment;
import com.magicode.cms.entiy.base.User;
import com.magicode.common.dao.ICommonDaoService;
import com.magicode.common.dao.PageResults;
import com.magicode.portal.service.IPCommentService;

@Service("pCommentService")
@Transactional
public class PCommentServiceImpl implements IPCommentService {

	@Autowired
	@Qualifier("commonDaoService")
	private ICommonDaoService commonDaoService;

	@Override
	public PageResults listByNewsId(String id, Integer pageNo, Integer pageSize) {
		String hql = " from com.magicode.cms.entiy.base.NewsComment t "
				+ " left join fetch t.author "
				+ " left join fetch t.author.mainPic "
				+ " left join fetch t.news "
				+ " where t.news.id=? "
				+ " order by t.createTime desc";
		PageResults pageResults = commonDaoService.findPageByFetchedHql(hql, null, pageNo==null?1:pageNo, pageSize, new String[]{id});
		return pageResults;
	}

	/**
	 * 我接收到的评论
	 */
	@Override
	public PageResults myReceiveListByUserId(String userId, Integer pageNo, Integer pageSize) {
 		String hql = " from com.magicode.cms.entiy.base.NewsComment t "
				+ " left join fetch t.author "
				+ " left join fetch t.author.mainPic "
				+ " left join fetch t.replyComment" 
				+ " left join fetch t.replyComment.author "
				+ " left join fetch t.news "
				+ " where t.replyComment.author.id=? "
				+ " order by t.createTime desc";
		PageResults pageResults = commonDaoService.findPageByFetchedHql(hql, null, pageNo==null?1:pageNo, pageSize, new String[]{userId});
		return pageResults;
	}
	/**
	 * 我发出到的评论
	 */
	@Override
	public PageResults mySendListByUserId(String userId, Integer pageNo, Integer pageSize) {
		String hql = " from com.magicode.cms.entiy.base.NewsComment t "
				+ " left join fetch t.author "
				+ " left join fetch t.author.mainPic "
				+ " left join fetch t.news "
				+ " left join fetch t.replyComment "
				+" left join fetch t.replyComment.author "
				+ " where t.author.id=? "
				+ " order by t.createTime desc";
		PageResults pageResults = commonDaoService.findPageByFetchedHql(hql, null, pageNo==null?1:pageNo, pageSize, new String[]{userId});
		return pageResults;
	}
	
	
	@Override
	public NewsComment createByNewsId(HttpSession session, String newsId, User user, String text) throws UnsupportedEncodingException {
		NewsComment comment = new NewsComment();
		News news = (News) this.commonDaoService.get(News.class, newsId);
		if(user != null){
			comment.setAuthor(user);
		}else{
			comment.setGuestName(this.getGuestName(session));
		}
		comment.setNews(news);
		comment.setText(text.getBytes("UTF-8"));
		comment.setCreateTime(new Date());
		this.commonDaoService.merge(comment);
		Long size=this.getsize(newsId);
		return comment;
	}

	@Override
	public NewsComment replyByCommentId(HttpSession session, String commentId, String newsId, User user, String text, String type) throws UnsupportedEncodingException {
		NewsComment reply = new NewsComment();
		NewsComment comment = new NewsComment();
		comment.setId(commentId);
		News news = (News) this.commonDaoService.get(News.class, newsId);
		news.setCommentsCount(news.getCommentsCount()+1);
		this.commonDaoService.update(news);
		if(user != null){
			reply.setAuthor(user);
		}else{
			reply.setGuestName(this.getGuestName(session));
		}
		reply.setAuthor(user);
		reply.setNews(news);
		reply.setReplyComment(comment);
		if(text!=null){
			reply.setText(text.getBytes("UTF-8"));
		}
		reply.setCreateTime(new Date());
		reply = (NewsComment) this.commonDaoService.merge(reply);
		Hibernate.initialize(reply.getAuthor());
		Hibernate.initialize(reply.getAuthor().getMainPic());
		Hibernate.initialize(reply.getNews());
//		String hql = " from com.magicode.cms.entiy.base.NewsComment t left join fetch t.author join fetch t.news where t.id=?";
//		reply = (NewsComment) this.commonDaoService.getByHQL(hql, reply.getId());
		return reply;
	}

	@Override
	public Attitude addAttitude(HttpSession session, String commentId, String newsId, User user, String text, String type) throws UnsupportedEncodingException {
		Attitude attitude = new Attitude();
		String hql = " from com.magicode.cms.entiy.base.Dictionary t where 1=1 ";
		if("zan".equals(type))
			hql += " and t.code='Zan' ";
		else
			hql += " and t.code='Cai' ";
//			+ "t.type='AttitudeType' ";//暂不支持
		if(commentId!=null && commentId.length()>0 && !"null".equals(commentId)){//commentId不为空时，表示该赞和踩是针对评论的
			NewsComment comment = (NewsComment) this.commonDaoService.get(NewsComment.class, commentId);
			//更新赞和踩的个数
			if("zan".equals(type)){
				if(comment.getAttZan()!=null)
					comment.setAttZan(comment.getAttZan()+1);
				else
					comment.setAttZan(1);
			}else{
				if(comment.getAttCai()!=null)
					comment.setAttCai(comment.getAttCai()+1);
				else
					comment.setAttCai(1);
			}
			this.commonDaoService.update(comment);
			attitude.setNewsComments(comment);
		}else if(commentId!=null && "null".equals(commentId) && newsId!=null && newsId.length()>0){//newsId不为空时，表示该赞和踩是针对文章的
			News news = (News) this.commonDaoService.get(News.class, newsId);
			//更新赞和踩的个数
			if("zan".equals(type)){
				if(news.getAttZan()!=null)
					news.setAttZan(news.getAttZan()+1);
				else
					news.setAttZan(1);
			}else{
				if(news.getAttCai()!=null)
					news.setAttCai(news.getAttCai()+1);
				else
					news.setAttCai(1);
			}
			this.commonDaoService.update(news);
			attitude.setNews(news);
		}
		if(user != null){
			attitude.setAuthor(user);
		}else{
			attitude.setGuestName(this.getGuestName(session));
		}
		Dictionary dictionary = (Dictionary) this.commonDaoService.getByHQL(hql, null);
		attitude.setAuthor(user);
		attitude.setType(dictionary);
		attitude.setCreateTime(new Date());
		attitude = (Attitude) this.commonDaoService.merge(attitude);
		return attitude;
	}
	
	private String getGuestName(HttpSession session){
		String guest_name = (String) session.getAttribute("guest_name");
		if(guest_name!=null){
			return guest_name;
		}else{
			guest_name = "传媒人";
			Random random = new Random();
			guest_name = guest_name + random.nextInt(9999);
			session.setAttribute("guest_name", guest_name);
			return guest_name;
		}
	}

	@Override
	@Transactional
	public void deleteCommetById(String commentid) { 
		NewsComment obj = (NewsComment) commonDaoService.get(NewsComment.class, commentid);
		if(null!=obj){
			try {
				commonDaoService.delete(obj);
				News news = (News) this.commonDaoService.get(News.class, obj.getNews().getId());
				news.setCommentsCount(news.getCommentsCount()-1-obj.getRelateReplyCommonts().size());
				this.commonDaoService.update(news);
			} catch (Exception e) {
				e.printStackTrace();
			}
			
		}
	}

	@Override
	public Long getUserComment(String userid) {
		String hql = " select count(t.id) from "+NewsComment.class.getName()+" t where t.author.id='"+userid+"'";
		return commonDaoService.countByHqlMap(hql, null);
	}

	@Override
	public Long getsize(String newsId) {
		String hql="select count(t.id) from "+NewsComment.class.getName()+" t where t.news.id='"+newsId+"'";
		return commonDaoService.countByHqlMap(hql, null);
	}
	
	
}
